import Vue from 'vue';
import Router from 'vue-router';
import utils from 'common/src/utils/utils';
import store from 'common/src/store/index';
import {
  MessageBox
} from 'element-ui';

import {
  callbackUrl
} from 'common/src/api/payment';

import { currentAuthId } from "common/src/api/session";

Vue.use(Router);

import {
  fetch,
} from 'common'

import ssologin from 'common/src/views/template'
import login from 'common/src/views/login'
import accountFreeze from 'common/src/views/login/freeze';//账号冻结页面
import Workbench from 'common/src/router/subRouters/workbench'
import Welcome from 'common/src/router/subRouters/welcome'
import Screen from 'common/src/router/subRouters/screen'
import systemsetting from 'common/src/router/subRouters/systemsetting'
import publicModule from 'common/src/router/subRouters/publicmodule'
import newermgr from 'common/src/router/subRouters/newermgr'
import StudentRegisterMgr from 'common/src/router/subRouters/studentregister';

let routes = [{
  path: '/',
  name: 'root',
  redirect: 'Workbench'
  },
  {
      path: '/ssologin',
      name: 'ssologin',
      component: ssologin
  },
  {
    path: '/login',
    name: 'login',
    redirect: store.state.ssourl
  },
  {
    path: '/localLogin',
    name: 'localLogin',
    component: login
  },
  {
    path:'/accountFreeze',
    name:'accountFreeze',
    component:accountFreeze
  },
  Workbench,
  Welcome,
  ...Screen,
  systemsetting,
  publicModule,
  newermgr,
  StudentRegisterMgr
]

// console.log(routes);
const router = new Router({
    mode: 'history',
    routes: routes
});

fetch.initFun(window.vueApp,router)

const showMessageBox = function () {
  MessageBox.confirm('您无权限访问该功能，如有疑问，请联系系统管理员。', '提示', {
    confirmButtonText: '确定',
    closeOnClickModal: false,
    showClose: false,
    showCancelButton: false,
    closeOnPressEscape: false,
    type: 'warning'
  })
}
router.beforeEach((to, from, next) => {
  let toParams = to.query;
  if (toParams.sign && toParams.data) {
    // 同济大学支付回调
    // to.fullPath = to.fullPath.substring(0, to.fullPath.indexOf("?"));
    // 请求后台
    callbackUrl(toParams);
  }
  utils.title(to.meta.label);
  const sessionid = store.getters.getSessionId();
  const isLogin = JSON.parse(localStorage.getItem('isLogin'));
  let userInfo = JSON.parse(localStorage.getItem('user'));
  if (!userInfo) {
    userInfo = {
      type: 3
    };
  }
  const userType = userInfo.type;
  if (!isLogin) {
    if (to.path === "/ssologin" || to.path === "/locallogin" ||  to.path === "/accountFreeze") {
      next();
    } else if (userType === 3) {
      next({
        path: '/locallogin'
      });
    } else {
      next({
        path: '/ssologin'
      });
    }
  } else if (
    !sessionid &&
    (to.path === '/ssologin' || to.path === '/locallogin')
  ) {
    next();
  } else if (!sessionid && to.path !== '/locallogin') {
    setTargetUrl(to.path);
    window.location.href = store.state.ssourl;
  } else if (
    sessionid &&
    isLogin &&
    (to.path === '/locallogin' || to.path === '/' || to.path === '/ssologin' || to.path === '/api/ssoservice/system/loginIn')
  ) {
    next({
      path: '/workbench'
    });
  } else if (sessionid &&
    isLogin && to.path === '/workbench') {
    next()
  } else {
    /**
     * 校验路由处理思路
     * 不带参数的路由正常处理，带参数的路由以/为节点从右向左切割匹配
     */
    let
      i = 0,
      path,
      auths, //菜单列表
      authInfo, //匹配到的菜单对象
      SlashList; //匹配到的/个数
    path = to.path;
    SlashList = path.match(/[/]/g)
    auths = JSON.parse(localStorage.getItem('sessiondata')) ? JSON.parse(localStorage.getItem('sessiondata')).auths : [];
    while (i < SlashList.length) {
      authInfo = findItem(auths, (item) => item.urlPath === path)
      if (authInfo) break
      path = path.substring(0, path.lastIndexOf('/'))
      i++
    }
    i = 0
    if (authInfo) {
      currentAuthId({
        authId: authInfo.authId
      }).then((res) => {
        if (res.code == 200) {
          next();
          store.commit('set_menu_authInfo', res.data)
        } else {
          showMessageBox()
        }
      }).catch((err)=>{
        console.log(err)
      })
    } else {
      // showMessageBox()
      // 临时放开
      next()
    }
  }
});


function setTargetUrl(path) {
  utils.setCookie('target_url', path);
}
function findItem(list, fn) {
  return list.find(fn)
}
export default router;
